package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.xxx.xbutler.data.RobotLoginMapper;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.RobotLogin;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 平台授权码回调接口
 *
 * <pre>
 * {
 *     "vcMerchantNo": "202204240052135",
 *     "vcRobotWxId": "",
 *     "vcRobotSerialNo": "",
 *     "vcSerialNo": "20221104183245072098125944772",
 *     "nType": 1025,
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "nTimeStamp": 1667557965619,
 *     "Data": {
 *         "vcCodeUrl": "http://kfpt.oss-cn-hangzhou.aliyuncs.com/pc/QrCode/2022110406/4bcbe5e44df64ccf858be3469df70630.jpeg",
 *         "vcScanCodeUrl": "http://kfpt.oss-cn-hangzhou.aliyuncs.com/pc/QrCode/2022110406/4bcbe5e44df64ccf858be3469df70630.jpeg"
 *     }
 * }
 * </pre>
 */
@Slf4j
@Component
public class _1025Handler implements CallbackHandler {

    @Resource
    private RobotLoginMapper robotLoginMapper;

    @Override
    public String name() {
        return "平台授权码回调接口";
    }

    @Override
    public boolean supports(int type) {
        return type == 1025;
    }

    @Override
    public void handle(Callback callback) {
        LambdaQueryWrapper<RobotLogin> wrapper = new LambdaQueryWrapper<RobotLogin>()
                .eq(RobotLogin::getSerialNo, callback.getSerialNo());
        boolean exists = robotLoginMapper.exists(wrapper);
        if (!exists) {
            JSONObject data = (JSONObject) callback.getData();
            RobotLogin login = new RobotLogin()
                    .setSerialNo(callback.getSerialNo())
                    .setRobotId(callback.getRobotId())
                    .setRobotSerialNo(callback.getSerialNo())
                    .setCode(data.getString("vcCodeUrl"))
                    .setScanCode(data.getString("vcScanCodeUrl"))
                    .setCreatedTime(LocalDateTime.now());
            robotLoginMapper.insert(login);
        }
    }
}
